package com.hxd.service.impl;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.hxd.base.BaseServiceImpl;
import com.hxd.common.constant.Constants;
import com.hxd.common.utils.RedisUtils;
import com.hxd.entity.SysMenu;
import com.hxd.mapper.SysMenuMapper;
import com.hxd.service.SysMenuService;

/**
 * <p>
    * 菜单权限表 服务实现类
    * </p>
 *
 * @author zhoujw
 * @since 2019-12-12
 * @version v1.0
 */
@Service
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
	
	@Value("${token.expire}")
	private long expire;
	
	@Autowired
	private RedisUtils redisUtils;

	@Override
	public List<SysMenu> getUserMenuList(Integer userId) {
		return mapper.selectUserMenuList(userId);
	}
	
	@Override
	public List<SysMenu> saveUserMenuCache(Integer userId) {
		List<SysMenu> sysMenuList = getUserMenuList(userId);
		if(sysMenuList.size() != 0) {
			redisUtils.set(Constants.REDIS_USER_MENU_PRE + userId, sysMenuList, expire/1000);
		}
		return sysMenuList;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<SysMenu> getUserMenu(Integer userId) {
		Object obj = redisUtils.get(Constants.REDIS_USER_MENU_PRE + userId);
		if(null == obj) {
			return saveUserMenuCache(userId);
		}
		return (List<SysMenu>) obj;
	}
	
	public void removeMenuByUserId(Integer userId) {
		Set<String> keys = redisUtils.keys(Constants.REDIS_USER_MENU_PRE + userId);
		if(keys.size() == 0) {
			return ;
		}
		String[] keysArr = keys.toArray(new String[0]);
		redisUtils.del(keysArr);
	}

}
